import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import _ from "lodash";
import { Button, Form, Input, TreeSelect, Radio, Select, InputNumber } from "antd";
import { renderTreeNodes } from "@pkgs/Layout/utils";
import useFormatMessage from "@pkgs/hooks/useFormatMessage";
import { prefixCls } from "../config";
import { findNodePathById } from "../utils";
import request from "@pkgs/request";
import api from "@common/api";
import "./style.less";
import type { DiscoveryTableListType } from "../interface";

const FormItem = Form.Item;
const { Option } = Select;

const defaultFormData = {
  nid: "",
  name: "",
  type: "ucs",
  service_id: "",
  port: null,
  metrics_path: "",
  idc: "",
  url: "",
  target: "",
};

const getInitialValues = (initialValues: DiscoveryTableListType) => {
  return _.assignIn({}, defaultFormData, _.cloneDeep(initialValues));
};

const getCollectServiceData = async (nodeId: number) => {
  try {
    const data = await request(
      `${api.collect}/list?nid=${nodeId}&type=service&watch_range=review`
    );
    return data;
  } catch {}
};

const URLForm = (props: any) => {
  const intlFmtMsg = useFormatMessage();
  const initialValues = getInitialValues(props.initialValues);
  const { getFieldProps, getFieldDecorator } = props.form;
  const { treeData } = props;
  const [selectNodeId, setSelectNodeId] = useState<number>();
  const [collectServiceData, setCollectServiceData] = useState([]);

  useEffect(() => {
    if (!initialValues.nid) return;
    if (selectNodeId !== undefined) {
      getCollectServiceData(selectNodeId).then((res) => {
        res && setCollectServiceData(res);
      });
    } else {
      getCollectServiceData(initialValues.nid).then((res) => {
        res && setCollectServiceData(res);
      });
    }
  }, [treeData, selectNodeId, initialValues.nid]);

  const [submitLoading, setSubmitLoading] = useState(false);

  const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    props.form.validateFields((errors: any, values: any) => {
      if (errors) {
        console.error(errors);
        return;
      }
      setSubmitLoading(true);
      if (values.collect_path) {
        const { collect_path } = values;
        const newPath = findNodePathById(treeData, collect_path);
        values.collect_path = newPath;
      }
      if (values.service_id == '') {
        values.service_id = 0
      }
      props.onSubmit(values).catch(() => {
        setSubmitLoading(false);
      });
    });
    setSubmitLoading(false);
  };

  return (
    <div className={`${prefixCls}-zeus-discovery-form`}>
      <Form layout="horizontal" onSubmit={handleSubmit}>
        <FormItem
          label={<strong>{intlFmtMsg({ id: "collect.common.node" })}</strong>}
        >
          {getFieldDecorator("nid", {
            initialValue: initialValues.nid,
            rules: [{ required: true, message: "请选择节点！" }],
          })(
            <TreeSelect
              style={{ width: 500 }}
              showSearch
              allowClear
              treeDefaultExpandAll
              treeNodeFilterProp="path"
              treeNodeLabelProp="path"
              onChange={(value: number) => {
                setSelectNodeId(value);
              }}
              dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
            >
              {renderTreeNodes(treeData, "treeSelect")}
            </TreeSelect>
          )}
        </FormItem>

        <FormItem
          label={
            <>
              <strong>发现通道:</strong>
              <span>prometheus的任务执行通道，一般选ucs</span>
            </>
          }
        >
          {getFieldDecorator("type", {
            initialValue: initialValues.type,
          })(
            <Radio.Group>
              <Radio value="ucs">UCS</Radio>
              <Radio value="exporter">exporter</Radio>
              <Radio value="instance">Instance</Radio>
            </Radio.Group>
          )}
        </FormItem>

        <FormItem
          label={
            <>
              <strong>服务名称:</strong>
              <span>prometheus采集里的app tag，供grafana配图筛选</span>
            </>
          }
        >
          <Input
            {...getFieldProps("name", {
              initialValue: initialValues.name,
              rules: [{ required: true, message: "必填项！" }],
            })}
            style={{ width: 500 }}
          />
        </FormItem>

        <FormItem
          label={
            <>
              <strong>归属服务:</strong>
              <span>可挂载至特定服务，服务配置见 采集配置→服务</span>
            </>
          }
        >
          {getFieldDecorator("service_id", {
            initialValue: initialValues.service_id,
          })(
            <Select style={{ width: 500 }}>
              {collectServiceData.map((item: any) => (
                <Option value={item.id} key={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          )}
        </FormItem>

        <FormItem
          label={
            <>
              <strong>监控端口:</strong>
              <span>采集监控指标的端口号</span>
            </>
          }
        >
          <InputNumber
            {...getFieldProps("port", {
              initialValue: initialValues.port,
              rules: [{ required: true, message: "必填项！" }],
            })}
            style={{ width: 500 }}
          />
        </FormItem>

        <FormItem
          label={
            <>
              <strong>监控路径:</strong>
              <span>采集指标的路径，一般为/metrics</span>
            </>
          }
        >
          <Input
            {...getFieldProps("metrics_path", {
              initialValue: initialValues.metrics_path,
              rules: [{ required: true, message: "必填项！" }],
            })}
            style={{ width: 500 }}
          />
        </FormItem>

        <FormItem
          label={
            <>
              <strong>所属机房:</strong>
              <span>必填，本次采集的指标来自哪个机房，例如zzzc zzdt等</span>
            </>
          }
        >
          <Input
            {...getFieldProps("idc", {
              initialValue: initialValues.idc,
            })}
            style={{ width: 500 }}
          />
        </FormItem>

        <FormItem
          label={
            <>
              <strong>发现URL:</strong>
              <span>可以从这个API获取机器列表，只支持get且无认证模式</span>
            </>
          }
        >
          <Input
            {...getFieldProps("url", {
              initialValue: initialValues.url,
            })}
            style={{ width: 500 }}
          />
        </FormItem>

        <FormItem
          label={
            <div className="url-item-label">
              <strong className="url-target-strong">target:</strong>
              <span className="url-target-span">
                url的response
                body必须是json；target指定的字段名必须在body中可解析到，且对应的格式为一个列表，比如response为
                {"{"}"node":["ip2","ip1"]{"}"},target填写node，response为{"{"}
                "node":{"{"}"ips":{"{"}"ip1","ip2"{"}"}
                {"}"}
                {"}"}，则target填写node.ips
              </span>
            </div>
          }
        >
          <Input
            {...getFieldProps("target", {
              initialValue: initialValues.target,
            })}
            style={{ width: 500 }}
          />
        </FormItem>

        <FormItem wrapperCol={{ offset: 6 }} style={{ marginTop: 24 }}>
          <Button type="primary" htmlType="submit" loading={submitLoading}>
            {intlFmtMsg({ id: "form.submit" })}
          </Button>
          <Button style={{ marginLeft: 8 }}>
            <Link
              to={{
                pathname: "/prometheus/discovery",
                search: window.location.search,
              }}
            >
              {intlFmtMsg({ id: "form.goback" })}
            </Link>
          </Button>
        </FormItem>
      </Form>
    </div>
  );
};

export default Form.create()(URLForm);
